import 'package:http/http.dart' as http;
import '../model/api_response.dart';
import '../model/order.dart';
import '../util/http_client.dart';
import '../util/parser_utils.dart';

class OrderApi {
  // 获取用户订单
  static Future<ApiResponse<List<Order>>> getUserOrders(String userId) async {
    try {
      final response = await HttpClient.get("/users/$userId/orders");
      return ParserUtils.parseObjectResponse<List<Order>>(
        response,
          parser: (json) => json
              .map((e) => Order.fromJson(e as Map<String, dynamic>))
              .toList() as List<Order>
      );
    } catch (e) {
      print("Failed to get user orders: $e\n");
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to get user orders: $e",
      );
    }
  }

  // 创建订单
  static Future<ApiResponse<Order>> createOrder(Order order) async {
    try {
      final orderData = order.toJson()..remove('id');

      final response = await HttpClient.post(
        "/orders",
        body: orderData,
      );

      return ParserUtils.parseObjectResponse<Order>(response, parser: (json)=>Order.fromJson(json));


    } catch (e) {
      return ApiResponse(
        data: null,
        status: 500,
        message: "Failed to create order: $e",
      );
    }
  }
}